package com.module.user.ui.me

import android.content.Intent
import android.os.Process
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.common.app.base.AppBackPressedFragment
import com.common.app.core.RouterHub
import com.common.app.data.bean.DialogButBean
import com.common.app.data.bean.KeyBundle
import com.common.app.dialog.CommonDialog
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.KeyPre
import com.common.app.data.bean.user.UserBean
import com.common.app.dialog.SelectCalendarDialog
import com.common.app.helper.*
import com.common.app.utls.TimeUtils
import com.common.base.app.activity.BaseVMActivity
import com.common.base.app.extras.*
import com.common.base.utils.*
import com.common.base.utils.ViewUtils.getColor
import com.common.base.widget.SCheckBox
import com.common.base.widget.popup.RecyclerPopupWindow
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.listener.CusBleDeviceInfoExpandListener
import com.module.ble.listener.CusConnectBleDeviceExpandListener
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.AizoSDKUtil.getBleBindingMac
import com.module.ble.utils.DeviceFirmType
import com.module.ble.utils.LightingEffectConfig
import com.module.ble.ui.colorSelection.SelectLightColorDialog
import com.module.user.R
import com.module.user.databinding.UserFragmentMeBinding
import com.module.user.ui.info.PersonInfoActivity
import com.module.user.ui.setting.SettingActivity
import com.module.user.ui.version.VersionActivity
import com.module.user.ui.feedback.ProblemFeedbackActivity
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/29
 * <p>
 * 描述：我的模块首页
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_ME_FRAGMENT)
class MeFragment : AppBackPressedFragment<UserFragmentMeBinding, MeViewModel>(),
    View.OnClickListener,
    CusConnectBleDeviceExpandListener, CusBleDeviceInfoExpandListener {

    override fun getViewModel() = MeViewModel::class.java
    override fun getViewBinding() = UserFragmentMeBinding.inflate(layoutInflater)

    private var popList: RecyclerPopupWindow<String>? = null

    private val classicsFooter by lazy { ClassicsFooter(requireActivity()) }

    private val intelligentTouchOptionAdapter by lazy { IntelligentTouchOptionAdapter() }

    private val selectCalendarDialog by lazy { SelectLightColorDialog(requireActivity()) }

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewBinding.statusView)

        //上下拉刷新
        getRefreshFooter()?.let { mViewBinding.pdView.setRefreshFooter(it) }
        mViewBinding.pdView.setRefreshHeader(
            ClassicsHeader(requireActivity())
                .setAccentColor(
                    ContextCompat.getColor(requireActivity(), R.color.white_80)
                )
        )
        classicsFooter.setAccentColor(
            ContextCompat.getColor(
                requireActivity(),
                R.color.color_999999
            )
        )
        mViewBinding.pdView.setRefreshFooter(classicsFooter)

        mViewBinding.hrvIntelligentTouch.adapter = intelligentTouchOptionAdapter
    }

    override fun initEvents() {
        super.initEvents()

        AizoSDKUtil.addConnectBleDeviceExpandListener(this)
        AizoSDKUtil.addBleDeviceInfoExpandListener(this)
        mViewBinding.userSetting.setOnClickListener(this)//切换环境
        LiveEventBus.get(KeyEvents.KEY_USER_LOGIN_SUCCESS).observe(this) {
            getUserInfo()
            lazyInitData()
        }

        LiveEventBus.get(KeyEvents.KEY_REQUEST_USER_INFO_DATA).observe(this) {
            initUserData()
        }

        mViewBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                mViewBinding.pdView.finishLoadMore()
                mViewBinding.pdView.finishLoadMoreWithNoMoreData()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                getUserInfo()
            }
        })

        mViewModel.intelligentTouchOptionData.observe(this){
            intelligentTouchOptionAdapter.setList(it)
        }

        mViewBinding.imgHead.setOnClickListener(onClick = this)
        mViewBinding.vPerInfoClick.setOnClickListener(onClick = this)
        mViewBinding.btnAddDevice.setOnClickListener(onClick = this)
        mViewBinding.imgRingType.setOnClickListener(onClick = this)
        mViewBinding.imgBotCardBg.setOnClickListener(onClick = this)
        mViewBinding.kvSetting.setOnClickListener(onClick = this)
        mViewBinding.kvGuide.setOnClickListener(onClick = this)
        mViewBinding.kvAbout.setOnClickListener(onClick = this)
        mViewBinding.kvFeedback.setOnClickListener(onClick = this)

//        // 设置开关状态变化监听
//        mViewBinding.switchEnable.setOnCheckedChangeListener(object : SCheckBox.OnCheckedChangeListener{
//            override fun onCheckedChange(view: View?, isChecked: Boolean) {
//                SpUtilsManagement.putBoolean(KeyPre.KEY_INTELLIGENT_TOUCH_OPEN_STATE,isChecked)
//                SpUtilsManagement.putInt(KeyPre.KEY_INTELLIGENT_TOUCH_TYPE, 0)
//                intelligentTouchOptionAdapter.notifyDataSetChanged()
//            }
//
//        })

        intelligentTouchOptionAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.btnOtherConfig->{
//                    selectCalendarDialog.show(intelligentTouchOptionAdapter.data[position].id)
                    RouterHelper.navigationPostcard(RouterHub.ROUTER_SELECT_COLOR)
                        .withInt(KeyBundle.BUNDLE_KEY, intelligentTouchOptionAdapter.data[position].id)
                        .navigation()
                }
                R.id.switchEnable->{
                    intelligentTouchOptionAdapter.data[position].let {
                        it.isSelect = !it.isSelect
                        when(it.id){
                            LightingEffectConfig.TYPE_LIGHTING_TIMING->SpUtilsManagement.putBoolean(KeyPre.KEY_LIGHTING_TIMING_VALUE,it.isSelect)
                            LightingEffectConfig.TYPE_LIGHTING_GESTURE->SpUtilsManagement.putBoolean(KeyPre.KEY_LIGHTING_GESTURE_VALUE,it.isSelect)
                            LightingEffectConfig.TYPE_LIGHTING_SPORTS->SpUtilsManagement.putBoolean(KeyPre.KEY_LIGHTING_SPORTS_VALUE,it.isSelect)
                        }
                    }
                    intelligentTouchOptionAdapter.notifyItemChanged(position)
                }
            }
        }
    }

    override fun onDestroy() {
        AizoSDKUtil.removeConnectBleDeviceExpandListener(this)
        AizoSDKUtil.removeBleDeviceInfoExpandListener(this)
        super.onDestroy()
    }

    override fun lazyInitData() {
        super.lazyInitData()
        UserHelper.isLogin().yes {

        }
    }

    override fun onSupportVisible() {
        super.onSupportVisible()
        StatusBarUtils.setStatusBarForegroundColor(requireActivity(), true)
        UmengAgentHelper.onEvent(EventUmengAgent.visit_mine_main)
        initUserData()
        getUserInfo()
//        setText(mViewBinding.tvUntieBle, "连接中。。。")
        checkBindingDevice()
        AizoSDKUtil.getDevicePowerState()
//        setText(mViewBinding.mRingNameTv,AizoSDKUtil.getBindRingInfo()?.ringFirm)
    }

    override fun onSupportInvisible() {
        super.onSupportInvisible()
    }

    private fun getUserInfo() {
        //未登录
        if (!UserHelper.isLogin()) {
            return
        }
        mViewModel.getUserInfo().observe(this) {
            finishPdView()
            it.isSuccess().yes {
                updateUser(it.Data)
            }
        }
    }

    //更新用户信息
    private fun updateUser(user: UserBean?) {
        UserHelper.updateUser(UserHelper.getUser(), user)
    }

    private fun initUserData() {
        UserHelper.getUser()?.let {
            mViewBinding.imgHead.loadCircle(it.avatar_url)
        } ?: let {
            mViewBinding.imgHead.loadId(R.drawable.common_user_def_head_icon, 100f)
        }
    }

    override fun onClick(v: View?) {

        //切换环境
        if (mViewBinding.userSetting == v) return showDevelopPopupWindow()

        when (v) {
            //个人资料
            mViewBinding.vPerInfoClick -> {
                UserHelper.checkLogin().no { return@onClick }
                requireActivity().startActivity<PersonInfoActivity>(false)
            }

            mViewBinding.btnAddDevice -> RouterHelper.navigation(RouterHub.ROUTER_BIND_GUIDE)
            mViewBinding.imgRingType -> RouterHelper.navigation(RouterHub.ROUTER_RING_INFO_ACTIVITY)
            mViewBinding.imgBotCardBg -> {
                when (mViewBinding.tvBotCard.text.trim()) {
                    getString(R.string.user_ring_info_hint) -> RouterHelper.navigation(RouterHub.ROUTER_RING_INFO_ACTIVITY)
                    getString(R.string.ble_to_add_device) -> RouterHelper.navigation(RouterHub.ROUTER_BIND_GUIDE)
                }
            }

            mViewBinding.imgHead -> {
                UserHelper.getUser()?.let {
                    RouterHelper.navigation(RouterHub.ROUTER_COM_PER_INFO_ACTIVITY)
                }
            }
            mViewBinding.kvSetting -> requireActivity().startActivity<SettingActivity>(false)
            mViewBinding.kvGuide -> requireActivity().startActivity<VersionActivity>(false)
            mViewBinding.kvAbout -> requireActivity().startActivity<VersionActivity>(false)
            mViewBinding.kvFeedback -> requireActivity().startActivity<ProblemFeedbackActivity>(false)
        }

    }

    //切换开发环境
    fun showDevelopPopupWindow() {
        val array = arrayListOf("线上", "测试", "开发8086", "开发8087")
        popList = RecyclerPopupWindow(activity, array, AppUtils.getColor(R.color.color_080808))
        popList?.setSelectColor(AppUtils.getColor(R.color.colorPrimaryDark))
        popList?.setPosition(DebugUtils.getCurrentEnvModel() - 1)
        popList?.setSelectColor(getColor(R.color.red))
        popList?.setOnItemClickListener {
            showMsgDialog(it)
            popList?.dismiss()
        }
        popList?.show(activity)
    }

    private fun showMsgDialog(type: Int) {
        CommonDialog.newInstance().setTitle("提示").setContent("切换环境APP重启才会生效,是否继续？")
            .setOnCommonDialogListener(object :
                CommonDialog.OnCommonDialogListener {
                override fun onClick(dialog: CommonDialog, position: Int, data: DialogButBean) {
                    if (position > 0) {
                        when (type) {
                            0 -> DebugUtils.setCurrentEnvModel(EnvModel.RELEASE)
                            1 -> DebugUtils.setCurrentEnvModel(EnvModel.TEST)
                            2 -> DebugUtils.setCurrentEnvModel(EnvModel.DEV)
                            3 -> DebugUtils.setCurrentEnvModel(EnvModel.DEV2)
                        }
                        postDelay(200) {
                            LiveEventBus.get("key_logout_app").post(true)
//                            android.os.Process.killProcess(android.os.Process.myPid())
//                            exitProcess(0)
                            restart()
                        }
                    }
                }
            }).show(childFragmentManager)
    }

    /**
     * 重启应用
     */
    private fun restart() {
        try {
            Thread.sleep(1000)
        } catch (e: InterruptedException) {
            Log.e(BaseVMActivity.TAG, "error : $e")
        }
        val intent = activity?.packageManager?.getLaunchIntentForPackage(activity?.packageName!!)
        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        startActivity(intent)
        Process.killProcess(Process.myPid())
    }


    private fun checkBindingDevice() {
        getBleBindingMac().isNullOrEmpty().no {
            setVisibility(mViewBinding.imgRightCardTop, true)
            setVisibility(mViewBinding.tvRightCardBot, true)
            setVisibility(mViewBinding.btnAddDevice, false)
            setVisibility(mViewBinding.imgRingType, true)
            setText(mViewBinding.tvBotCard, R.string.user_ring_info_hint)
            when (AizoSDKUtil.getRingFirm()) {
                DeviceFirmType.HDU_FIRM -> {
                    setImageResource(mViewBinding.imgRingType, R.drawable.common_ring_type_1_icon)
                }

                DeviceFirmType.YQ_FIRM -> {
                    setImageResource(mViewBinding.imgRingType, R.mipmap.ic_logo_launcher)
                }

                else -> {
                    setImageResource(mViewBinding.imgRingType, R.mipmap.ic_logo_launcher)
                }
            }
        }.otherwise {
            setViIn(mViewBinding.imgRightCardTop, false)
            setViIn(mViewBinding.tvRightCardBot, false)
            setVisibility(mViewBinding.imgRingType, false)
            setVisibility(mViewBinding.btnAddDevice, true)
            setText(mViewBinding.tvBotCard, R.string.ble_to_add_device)
        }
    }

    private fun finishPdView() {
        mViewBinding.pdView.finishRefresh()
        mViewBinding.pdView.finishLoadMore()
        mViewBinding.pdView.setNoMoreData(true)
    }


    fun connectStateUi(mType: Int) {
        setVisibility(mViewBinding.imgRightCardTop, true)
        setVisibility(mViewBinding.tvRightCardBot, true)
        when (mType) {//0已断开1连接中2已连接
            2 -> {
                setImageResource(mViewBinding.imgRightCardTop, R.drawable.user_ble_connected_icon)
                mViewBinding.tvRightCardBot.text = getString(R.string.common_ring_connected_hint)
            }

            else -> {
                setImageResource(
                    mViewBinding.imgRightCardTop,
                    R.drawable.user_ble_disconnected_icon
                )
                mViewBinding.tvRightCardBot.text = getString(R.string.common_ring_disconnected_hint)
            }
        }
    }

    override fun onConnect(macStr: String?) {
        connectStateUi(AizoSDKUtil.isConnect)
    }

    override fun onConnectError(macStr: String?, throwable: Throwable?, state: Int) {
        showToast("蓝牙连接失败, state：${state}, ${throwable?.message}")
    }

    override fun onDisconnect(macStr: String?) {
        connectStateUi(AizoSDKUtil.isConnect)
    }

    override fun onHandleDevice(type: Int, result: Boolean) {
        result.yes {
            checkBindingDevice()
        }
    }

    override fun onBoundDeviceResult(macStr: String, result: Boolean) {
    }

    override fun onDevicePowerState(electricity: String, workingMode: Int) {//0未充电1充电中other未充电
        setVisibility(mViewBinding.tvLeftCardTop, true)
        setText(mViewBinding.tvLeftCardTop, getString(R.string.common_ring_state_split, ("$electricity${getString(R.string.common_bfb_unit)}")))
        setTextColor(mViewBinding.tvLeftCardTop, if(electricity.toInt()<=10) getColor(R.color.c_f3607b) else getColor(R.color.c_12b2b2))
        (workingMode == 1).yes {
            mViewBinding.tvLeftCardBot.text = getString(R.string.common_ring_charging_hint)
            setVisibility(mViewBinding.tvLeftCardBot, true)
        }.otherwise {
            connectStateUi(AizoSDKUtil.isConnect)
            mViewBinding.tvLeftCardBot.text = ""
        }
    }

    override fun onGetDeviceInfo() {
    }
}